// hooks/field.ts
import { useCallback, useState } from 'react';

export const useField = (locale?: Locales) => {
  const [fields, setFields] = useState<Field[]>([]);

  // 加载字段列表
  const loadFields = useCallback(async (sheetId?: string) => {
    try {
      const fieldList = await Dingdocs.script.run('getSheetFields', sheetId);
      setFields(fieldList); // 直接在 hook 内部更新状态
      return fieldList;
    } catch (error: any) {
      console.error('Load fields failed:', error);
      throw error;
    }
  }, []);

  // 添加字段
  const handleAddField = useCallback(async (
    fields: Field[],
    setLoading: (loading: boolean) => void
  ) => {
    if (!locale) return;
    
    const random = Math.floor(Math.random()*100);
    const name = `新字段${random}`;
    
    if (fields.some((field: Field) => field.name === name)) {
      alert(`字段名称${name}已存在`);
      return;
    }
    
    setLoading(true);
    try {
      await Dingdocs.script.run('addField', name.trim(), 'text');
      console.log(`✅ ${locale.addFieldSuccess}`);
      await loadFields(); // 直接调用内部的 loadFields
    } catch (error: any) {
      alert(`${locale.operationFailed}: ${error.message}`);
    } finally {
      setLoading(false);
    }
  }, [locale, loadFields]); // 添加 loadFields 到依赖数组

  // 删除字段
  const handleDeleteField = useCallback(async (
    fieldId: string, 
    fieldName: string, 
    isPrimary: boolean
  ) => {
    if (!locale) return;
    
    if (isPrimary) {
      alert(locale.cannotDeletePrimaryKeyField);
      return;
    }

    if (!window.confirm(`${locale.confirmDeleteField} "${fieldName}" ${locale.confirmDelete}？${locale.dataWillBeLost}。`)) {
      return;
    }

    try {
      await Dingdocs.script.run('deleteField', fieldId);
      console.log(`✅ ${locale.deleteFieldSuccess}`);
      await loadFields(fieldId); // 直接调用内部的 loadFields
    } catch (error: any) {
      alert(`${locale.deleteFieldFailed}: ${error.message}`);
    }
  }, [locale, loadFields]); // 添加 loadFields 到依赖数组

  return {
    fields,
    setFields,
    loadFields,
    handleAddField,
    handleDeleteField
  };
};